// pages/demo07/clip/clip.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },
  //绘制图像
  drawImage: function () {
    let ctx = this.ctx
    this.img = this.canvas.createImage()
    let img=this.img;
    img.crossOrigin = 'Anonymous'; //解决跨域问题
    img.onload = () => {
      console.log('成功')
      ctx.drawImage(img, 50,50)
    }
    img.onerror = (e) => {
      console.log('失败')
    }
    img.src = '/images/demo07/icon.jpg';
  },
  //还原
  resetImage:function(){
    let ctx = this.ctx
    let img = this.canvas.createImage()
    img.crossOrigin = 'Anonymous'; //解决跨域问题
    img.onload = () => {
      console.log('成功')
      ctx.drawImage(img, 50,50)
    }
    img.onerror = (e) => {
      console.log('失败')
    }
    img.src = '/images/demo07/sakura.jpg';
  },
  clearImage:function(){
    let ctx = this.ctx
    ctx.clearRect(0,0,300,300);
  },
  //剪裁
  clip: function () {
    let ctx = this.ctx
    let img=this.img;
    ctx.clearRect(0,0,300,300);
    ctx.beginPath()
    ctx.arc(150, 150, 100, 0, 2 * Math.PI)
    ctx.clip()
    ctx.drawImage(img, 50,50)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     //创建画布上下文
     let that = this
     const query = wx.createSelectorQuery()
     const newLocal = '#myCanvas';
     query.select(newLocal)
       .fields({
         node: true
       })
       .exec((res) => {
         const canvas = res[0].node
         that.canvas = canvas;
         that.ctx = canvas.getContext('2d')
          //tip: Canvas 2D（新接口）需要显式设置画布宽高 (默认为 300x150)
          canvas.width = 300;
          canvas.height = 300;
          that.drawImage();
       })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})